package com.tbit.uqbike.client.controller;

import com.tbit.uqbike.client.constant.ResponseCode;
import com.tbit.uqbike.client.dao.core.UserToAgentDao;
import com.tbit.uqbike.client.exception.BaseException;
import com.tbit.uqbike.client.pojo.GiftCardUser;
import com.tbit.uqbike.client.pojo.User;
import com.tbit.uqbike.client.pojo.UserToAgent;
import com.tbit.uqbike.client.service.GeoService;
import com.tbit.uqbike.client.service.GiftCardUserService;
import com.tbit.uqbike.client.service.TokenService;
import com.tbit.uqbike.client.util.OutputUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

/**
 * 区域礼品卡用户余额
 *
 * @Author: chen
 * @Description: 区域礼品卡用户余额
 * @Date: 创建于 15:28 2020/1/3
 */
@Controller
@RequestMapping("/giftCardUser")
public class GiftCardUserController {
    @Autowired
    private GeoService geoService;
    @Autowired
    private GiftCardUserService giftCardUserService;
    @Autowired
    private TokenService tokenService;
    @Autowired
    private UserToAgentDao userToAgentDao;

    /**
     * 获取用户区域虚拟金额
     *
     * @param token       令牌
     * @param adAccountId 区域id
     * @param accountId   品牌id
     * @param lo          经度
     * @param la          纬度
     * @param mapType     地图类型
     * @param response    响应
     * @ignoreParams request
     */
    @RequestMapping("/getByLocation")
    public void getByLocation(String token, Integer adAccountId, Integer accountId, Double lo, Double la, Integer mapType, HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> map = new HashMap<String, Object>();

        try {
            //Assert.notNull(adAccountId, "-10001", "品牌id不能为空");
            if (adAccountId == null) {
                Integer agentId = geoService.getBelongAccount(accountId, lo, la, mapType);
                if (agentId == null) {
                    User user = tokenService.getUser(token);
                    if (user != null) {
                        UserToAgent userToAgent = userToAgentDao.getByUserId(user.getUserId());
                        if (userToAgent != null) {
                            agentId = userToAgent.getAccountId();
                        }
                    }
                }
                adAccountId = agentId;
            }

            User user = tokenService.getUser(token);
            GiftCardUser giftCardUser = giftCardUserService.getByUserId(user.getUserId(), adAccountId);
            map.put(ResponseCode.DATA, giftCardUser);
            map.put(ResponseCode.RET, ResponseCode.SUCC);
        } catch (BaseException e) {
            ResponseCode.printException(map, e, request);
        }

        OutputUtil.renderText(request, response, map);
    }

}
